<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>判断css和js是否加载完毕</title>
</head>

<body>
    <div class="box"></div>
    <script>
        // 1. 判断js 
        function loadScript (url, callback) {
            const scriptEle = document.createElement('script')
            scriptEle.type = 'text/javascript'
            scriptEle.src = url
            scriptEle.onload = function () {
                callback()
            }
            document.body.appendChild(scriptEle)
        }

        // 调用时
        const url = '../../js/common.js'
        loadScript(url, function () {
            console.log(111) // 这一行后执行
            // ...加载完成后执行的代码
        })
        console.log(222) // 这一行先执行

        // 2. 判断css 
        // (1) 通过onload
        const cssEle = document.createElement('link')
        cssEle.rel = 'stylesheet'
        cssEle.href = '../../css/test.css'
        cssEle.onload = function () {
            console.log(333) // 这一行后执行
        }
        const head = document.querySelector('head')
        head.appendChild(cssEle)
        console.log(444) // 这一行先执行

        // (2) 通过轮询
        const callback = () => console.log('css加载完成')
        const cssEle2 = document.createElement('link')
        cssEle2.rel = 'stylesheet'
        cssEle2.href = '../../css/test2.css'
        head.appendChild(cssEle2)

        ; (function check () {
            if (cssEle.sheet && cssEle.sheet.cssRules && cssEle.sheet.cssRules.length) { // 通过属性来判断css加载完成
                cssEle2.setAttribute('lay-status', 'done')
                callback()
            } else {
                cssEle2.setAttribute('lay-status', 'creating')
                setTimeout(function () {
                    check()
                }, 100)
            }
        }())

    </script>
</body>

</html>